#!/bin/bash
# **************
# 简单的部署脚本，通过git更新源码
# TODO deloy init,deloy update
# **************

USER=celery
GIT_BASE=/home/celery
CELERY_PROJECT_PATH=/opt/celeryproject
PATH=/usr/local/bin:$PATH


#创建用户
if [ ! $( id -nu $USER 2> /dev/null ) ]; then #用户不存在，把错误信息重定向
    useradd -m -s /sbin/nologin $USER
fi

## 创建目录，默认复制代码到/opt/celeryproject
if [ ! -d CELERY_PROJECT_PATH ]; then
    mkdir -p CELERY_PROJECT_PATH
    chown celery:celery CELERY_PROJECT_PATH
fi

# 初始化
if [ ! -d $GIT_BASE/celeryproject ]; then
    cd $GIT_BASE
    git clone https://git.oschina.net/wja513/celeryproject.git
fi

#更新
cd $GIT_BASE/celeryproject
git pull

# 覆盖源码
cp -R $GIT_BASE/celeryproject/proj $CELERY_PROJECT_PATH
cp $GIT_BASE/celeryproject/manage.py $CELERY_PROJECT_PATH

# 复制静态资源
python3 /opt/celeryproject/manage.py collectstatic --noinput


## 进程管理全部通过supervisor管理
# 重启celery worker（每台机器都有worker）
supervisorctl restart celery

# 重启celery beat（仅特殊机器有beat，保证仅有一台机器运行）
#celery_beat_count=$(ps aux | grep "celery beat" | grep -v "grep" | wc -l)
localhost_ip=$(/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:" | head -1)
#if [ $celery_beat_count -gt 0 ] && [ $localhost_ip=="10.100.14.27" ]; then
if [ $localhost_ip == "10.100.14.27" ]; then
    supervisorctl restart celerybeat
fi


# 重启uwsgi（不需要的机器不安装uwsgi）
if test -f /etc/supervisord.conf.d/uwsgi.conf ; then
    supervisorctl restart uwsgi
fi
